﻿using System;
using System.Linq;
using ZilLion.Service.Core.ConfigManager.Cache;
using ZilLion.Service.Core.ConfigManager.Helper;
using ZilLion.Service.Core.ConfigManager.Interface;

namespace ZilLion.Service.Core.ConfigManager.Attribute
{
    /// <summary>
    ///     配置provider来源标签
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, Inherited = false)]
    public class ConfigurationArgumentAttribute : System.Attribute
    {
        private IConfigProvider _providerInstance;



        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="configType"></param>
        /// <param name="providerType"></param>
        public ConfigurationArgumentAttribute(Type configType, Type providerType) : this(configType, providerType, 0)
        {
        }

        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="configType"></param>
        /// <param name="providerType"></param>
        /// <param name="refreshInterval"></param>
        public ConfigurationArgumentAttribute(Type configType, Type providerType, int refreshInterval)
        {
            ProviderType = providerType;
            var first = ConfigurationInstanceCache.Instance()
                .ConfigCustomProviderCache.Keys.FirstOrDefault(x => x.FullName == configType.FullName);
            if (first != null)
                ProviderType = ConfigurationInstanceCache.Instance()
                    .ConfigCustomProviderCache[first];
            ProviderInstance =  ConfigHelper.FastNew(ProviderType) as IConfigProvider;
            if (ProviderInstance != null) ProviderInstance.ConfigurationType = configType;
            RefreshInterval = refreshInterval;
        }

        /// <summary>
        ///     刷新间隔
        /// </summary>
        public int RefreshInterval { get; set; }

        /// <summary>
        ///     IConfigProvider  Type
        /// </summary>
        public Type ProviderType { get; set; }

        /// <summary>
        ///     IConfigProvider实例
        /// </summary>
        public IConfigProvider ProviderInstance
        {
            get { return _providerInstance; }
            set
            {
                _providerInstance = value;
                if (value.GetType() != ProviderType)
                    ProviderType = value.GetType();
            }
        }
    }

    /// <summary>
    ///     配置存在节点
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, Inherited = false)]
    public class ZilLionConfigSectionAttribute : System.Attribute
    {
        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="sectionName"></param>
        public ZilLionConfigSectionAttribute(string sectionName)
        {
            SectionName = sectionName;
        }

        /// <summary>
        ///     配置存在节点名称
        /// </summary>
        public string SectionName { get; set; }
    }
}